package com.nikmesoft.android.referendumfriend.activities;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.adapters.Group_select_adapter;
import com.nikmesoft.android.referendumfriend.models.ItemHobies;
import com.nikmesoft.android.referendumfriend.models.userhobies;
import com.nikmesoft.android.referendumfriend.service.AllHobbyHandler;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;

public class Group_select extends BaseActivity implements OnItemClickListener {

	Group_select_adapter adapter;
	ListView list;
	TextView txttieude;
	CheckBox cb;
	String truoc = "All Hobby";
	userhobies user;
	private ProgressDialog dialog;
	private WSLoader loader;
	String title = "";
	ArrayList<ArrayList<ItemHobies>> arr_hobby = new ArrayList<ArrayList<ItemHobies>>();
	ArrayList<String> tit = new ArrayList<String>();
	public static ArrayList<Integer> id_hobby = new ArrayList<Integer>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_all_hobby);
		list = (ListView) findViewById(R.id.list_all_hobby);
		txttieude = (TextView) findViewById(R.id.title_hobbyht);
		cb = (CheckBox) findViewById(R.id.cb_itemhobby2);
		dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");

		Bundle bun = (Bundle) getIntent().getExtras();
		user = (userhobies) bun.getSerializable("user");
		adapter = new Group_select_adapter(this, R.layout.item_hobby,
				user.getArr());

		ArrayList<ItemHobies> arr = new ArrayList<ItemHobies>();
		arr = user.getArr();
		arr_hobby.add(arr);

		tit = new ArrayList<String>();
		tit.add("All Hobby");
		txttieude.setText("All Hobby");

		list.setAdapter(adapter);
		list.setOnItemClickListener(this);
	}

	public void onItemClick(AdapterView<?> arg0, View v, int pos, long id) {
		if (user.get(pos).isHaschild()) {

			title = user.get(pos).getName();

			if (loader == null || loader.isCancelled()
					|| loader.getStatus() == Status.FINISHED) {
				loader = new WSLoader();
				loader.execute(String.valueOf(LoginHandler.result.getId()), String.valueOf(user.get(pos).getId()));
			}

		}
	}

	public void updatelist(ArrayList<ItemHobies> it, String title) {
		ArrayList<ItemHobies> arr = new ArrayList<ItemHobies>();
		arr = it;
		arr_hobby.add(arr);
		tit.add(title);

		txttieude.setText(title);
		adapter = new Group_select_adapter(this, R.layout.item_hobby, it);
		list.setAdapter(adapter);
		adapter.notifyDataSetChanged();

	}

	public void callBack(View v) {
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (user.getArr().size() == 0) {
			finish();
			return;
		}
		int i = tit.size();
		if (i == 1) {
			finish();
			return;
		}

		arr_hobby.remove(i - 1);
		tit.remove(i - 1);

		ArrayList<ItemHobies> arr = new ArrayList<ItemHobies>();
		arr = arr_hobby.get(i - 2);
		user.setArr(arr);
		String tt = tit.get(i - 2);
		arr_hobby.remove(i - 2);
		tit.remove(i - 2);
		updatelist(arr, tt);

	}

	public void callSave(View v) {
		WSLoader_Save load=null;
		if (load == null || load.isCancelled()
				|| load.getStatus() == Status.FINISHED) {
			load = new WSLoader_Save();
			load.execute(String.valueOf(LoginHandler.result.getId()));
		}
	}

	private String callWS(String id_user, String id_parent) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<getAllHobbies soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<GetAllHobbiesRequest xsi:type=\"rdf:GetAllHobbiesRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_parent xsi:type=\"xsd:int\">"
				+ id_parent
				+ "</id_parent>"
				+ "<id_user xsi:type=\"xsd:int\">"
				+ id_user
				+ "</id_user>"
				+ "</GetAllHobbiesRequest>"
				+ "</getAllHobbies>"
				+ "</soapenv:Body>" + "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	private String callWS_Save(String id_user, String id_hobby) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<addRemoveHobby soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<AddRemoveHobbyRequest xsi:type=\"rdf:AddRemoveHobbyRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:int\">"+id_user+"</id_user>"
				+ "<id_hobby xsi:type=\"xsd:int\">"+id_hobby+"</id_hobby>"
				+ "<action xsi:type=\"xsd:int\">1</action>"
				+ "</AddRemoveHobbyRequest>"
				+ "</addRemoveHobby>"
				+ "</soapenv:Body>" + "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	private userhobies xmlParser(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
			AllHobbyHandler handler = new AllHobbyHandler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();

		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
	private class WSLoader_Save extends AsyncTask<String, Integer,Void> {

		@Override
		protected Void doInBackground(String... params) {
			for (int i=0;i<id_hobby.size();i++)
			{
				callWS_Save(params[0],String.valueOf(id_hobby.get(i)));
			}
			return null;
		}



		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			
			dialog.dismiss();
			finish();
		}



		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

	}
	
	private class WSLoader extends AsyncTask<String, Integer, userhobies> {

		@Override
		protected userhobies doInBackground(String... params) {
			userhobies us = xmlParser(callWS(params[0], params[1]));
			return us;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(userhobies result) {

			super.onPostExecute(result);
			try {
				if (result.getErr() != null)
					toad(result.getErr().getErrorMsg());
				else {

					user = new userhobies();
					user = result;
					updatelist(user.getArr(), title);
				}
				dialog.dismiss();
			} catch (Exception ex) {
				dialog.dismiss();
				toad("No Internet Connection!");
			}

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}

	public void toad(String str) {
		CommonUtil.toastNotify(this, str);
	}

}
